package comms;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import Vis.Visualiser;

/**
 * Start a connection with the phone and then to the Kinect
 * 
 * @author norrielm
 *
 */
public class Communicator {

	/**
	 * Helper class to direct messages from C program to Phone
	 * and handle storage of Hotspots
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static boolean exiting = false;
	public static PhoneServer s;
	public static KinectClient c;
	private static Process p;
	private static InputStreamReader isr;
	private static BufferedReader br;
	private static Thread kinectThr;
	private static Thread clientThr;
	
	public static void main(String args[]) throws Exception {
		
		//visualise connections
		final Visualiser v = new Visualiser();
		v.setVisible(true);
		
		c = null; //gets data from kinect
		s = null; //sends data to phone
		
		//Start Kinect server
		kinectThr = new Thread(new Runnable(){
			private InputStream is;

			public void run() {
				try{
					p = Runtime.getRuntime().exec("KinectServer.exe", null);
					isr = new InputStreamReader(p.getInputStream());
					//is = p.getInputStream();
					//br = new Scanner(p.getInputStream());
					br = new BufferedReader(isr);
					c.setupKinectPanel();
				}catch(Exception e){
					System.err.println("Could not start server: " + e);
					e.printStackTrace();
				}
				
				try {
					while(!exiting){
						String line;
						if(!exiting && (line=br.readLine())!=null){
							System.out.println("[Kinect] [" + line + "]");
							
							//c.append("[Debug] (" + line + ")");
							
							if(line.contains("failed to receive a network buffer")){
								System.exit(0);
							}
							c.handleKinectMessage(line);
						}
						Thread.sleep(10);
					}
				} catch (IOException e) {
					e.printStackTrace();
					System.exit(0);
				} catch (InterruptedException e) {
					e.printStackTrace();
					System.exit(0);
				}
				exit(1);
				
			}
		});

		c = new KinectClient(v);			
		s = new PhoneServer(v);
		
		s.setClient(c);
		c.setServer(s);

		kinectThr.start();
		clientThr = new Thread(c);
		clientThr.start();	
		
		
		clientThr.join();
		kinectThr.join();
		
		v.setMenuItemAction(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
			s.disconnectAllDevices();	
				
			}
			
		});
	}
	
	public static void exit(int i){
		exiting = true;
		
		//client closed	
		if(i==0 && p!=null){
			p.destroy();
			p=null;
			try {
				br.close();
				isr.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		//kinect closed
		try {
			if(i==1 && c.clientAlive)
				c.closeClient();
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//System.exit(0);
	}
}